# == Schema Information
#
# Table name: sales_firm_leads
#
#  id         :integer          not null, primary key
#  firm_id    :integer
#  leads_type :integer
#  begin_at   :datetime
#  expire_at  :datetime
#  user_id    :integer
#  stage      :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Sales::FirmLead < ApplicationRecord
  LEADS_TYPE = {main: 1, cce: 2}
  STAGE = {sales: 1, cce: 2}

  attr_accessor :add_history_before_save

  belongs_to :user, :class_name=>'Base::User', foreign_key: 'user_id'

  extend Enumerize
  enumerize :leads_type, in: LEADS_TYPE,  predicates: {prefix: true}, scope: true

  before_save :add_history

  def grab_by(user_id = Base::Session.current_user_id)
    self.begin_at = Time.now
    self.expire_at = Time.now + 3.months
    self.user_id = user_id
    self.add_history_before_save = true
    self.save
  end

  def add_history(force = false)
    return unless self.add_history_before_save || force
    Log::LeadsHistory.create(
      firm_id: firm_id,
      leads_type: leads_type,
      from_user_id: user_id_was,
      to_user_id: user_id,
      that_begin_at: begin_at_was,
      that_expire_at: expire_at_was,
      that_stage: stage_was,
      created_by: Base::Session.current_user_id
    )
  end
end
